﻿using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.Security;
using SharingCenter.Web.Classes;
using System.Drawing;
using System.Drawing.Imaging;

namespace SharingCenter.Web.Services
{
    public class FileHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "application/json";
            //context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            string savedFileName = string.Empty;
            string strSaveLocation = context.Server.MapPath("~/Content/Uploads");
            if (!Directory.Exists(strSaveLocation))
            {
                Directory.CreateDirectory(strSaveLocation);
            }
            try
            {
                HttpPostedFile file = context.Request.Files["Filedata"];
                string strFileName = FormsAuthentication.HashPasswordForStoringInConfigFile(Path.GetFileName(file.FileName), "md5");
                string strExtension = Path.GetExtension(file.FileName).ToLower();
                savedFileName = DateTime.Now.Ticks + strExtension;
                file.SaveAs(strSaveLocation + "/" + savedFileName);

                Bitmap resized;
                string thumbFileName = strFileName + ".t" + strExtension;
                Utility.ImageUtility.ResizeImageByWidthOnly(700, file.InputStream, out resized);
                resized.Save(string.Format(@"{0}\{1}", strSaveLocation, thumbFileName), ImageFormat.Jpeg);

                //context.Request.Files[0].SaveAs(strSaveLocation);
                string response = "{ImagePath:'" + savedFileName + "',ThumbPath:'" + thumbFileName + "'}";
                context.Response.Write(response);
            }
            catch
            {
                context.Response.Write("");
            }
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}